package com.example.e_book.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.e_book.R;
import com.example.e_book.DAO.UserDAO;

public class RegisterActivity extends AppCompatActivity {

    private EditText usernameEditText;
    private EditText passwordEditText;
    private EditText confirmPasswordEditText;
    private UserDAO userDAO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        usernameEditText = findViewById(R.id.new_username);
        passwordEditText = findViewById(R.id.new_pass);
        confirmPasswordEditText = findViewById(R.id.confirm_password);
        userDAO = new UserDAO(this);

        Button registerButton = findViewById(R.id.register);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                String confirmPassword = confirmPasswordEditText.getText().toString();

                if (password.isEmpty() || username.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "用户名和密码不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!password.equals(confirmPassword)) {
                    Toast.makeText(RegisterActivity.this, "两次输入密码不一致！", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 检查用户名是否重复
                if (userDAO.isUsernameExists(username)) {
                    Toast.makeText(RegisterActivity.this, "用户名重复，注册失败！", Toast.LENGTH_SHORT).show();
                    return;
                }

                long result = userDAO.addUser(username, password);
                if (result == -1) {
                    Toast.makeText(RegisterActivity.this, "注册失败！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                    finish(); // 关闭注册页面，返回登录页面
                }
            }
        });

        Button backToLoginButton = findViewById(R.id.relogin);
        backToLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent); // 启动LoginActivity
                finish(); // 结束当前的RegisterActivity
            }
        });
    }
}